<?php

namespace app\common\service;

use app\common\service\Base;

class Target extends Base
{
	/**
	 * 获取某工厂某类型目标值
	 *
	 * @author KING
	 * @date 2018年6月23日
	 *
	 * @param integer $factoryId
	 * @param integer $type		类型（1月度件数，2月度金额，3月度加工费，4月度货期，5年度金额）
	 * @param integer $curDate
	 * @return number
	 */
	public function getTarget($factoryId, $type, $curDate='') {
		$where[] = [
			['factory_id', is_numeric($factoryId)?'=':'in', $factoryId],
			['type', '=', $type],
		];
		if ($curDate == '') {
			if (in_array($type, [1,2,3,4])) {
				$curDate = date('Ym');
			} elseif ($type == 5) {
				$curDate = date('Y');
			}
		}
		$where[] = ['cur_date', '=', $curDate];
		return db('target')->where($where)->sum('target');
	}

	/**
	 * 保存某目标值
	 *
	 * @author KING
	 * @date 2018年6月23日
	 *
	 * @param integer $factoryId
	 * @param integer $curDate
	 * @param integer $type
	 * @param integer $target
	 */
	public function saveTarget($factoryId, $curDate, $type, $target) {
		$where = [
			'factory_id' => $factoryId,
			'type' => $type,
			'cur_date' => $curDate,
		];
		$info = db('target')->where($where)->field('id')->find();
		$upData = ['target' => $target, 'update_time' => time()];
		if ($info) {
			$where = ['id' => $info['id']];
			return db('target')->where($where)->update($upData);
		} else {
			$upData = array_merge($upData, $where);
			$upData['create_time'] = time();
			return db('target')->insertGetId($upData);
		}
	}

}